//
//  VIPHomeViewController.swift
//  GhostWorld
//
//  Created by Kam on 2018/5/16.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit
import SnapKit

private let categoryViewHeight: CGFloat = 44

class VIPHomeViewController: BaseViewController {

  // MARK: - IBOutlets
  
  @IBOutlet private weak var categoryContainer: UIView!
  @IBOutlet private weak var topViewTopConstraint: NSLayoutConstraint!
  
  // MARK: - Private vars
  
  private let categoryView: CategoryView = .fromNib (
    titles: ["最新", "分类", "全部"],
    normalTitleColor: UIColor(fromRGB: 0x787878),
    highlightTitleColor: UIColor(fromRGB: 0xEDBF64),
    focusColor: UIColor(fromRGB: 0xEDBF64)
  )!
  
  private var currentSubViewController: VIPChildViewController?
  
  // MARK: - Private methods
  
  private func prepareUI() {
    categoryContainer.addSubview(categoryView)
    categoryView.delegate = self
    categoryView.snp.makeConstraints({ maker in
      maker.leading.top.trailing.bottom.equalTo(0)
    })
  }
  
  private func displaySubViewController(index: Int) {
    var vcName = ""
    switch index {
    case 0:
      // Latest
      vcName = "VIPLatestViewController"
    case 1:
      // Category
      vcName = "VIPCategoryViewController"
    case 2:
      // All
      vcName = "VIPAllViewController"
    default:
      break
    }

    if vcName.count > 0 {
      let storyboard = UIStoryboard(name: "VIP", bundle: nil)
      let vc = storyboard.instantiateViewController(withIdentifier: vcName) as! VIPChildViewController
      vc.view.backgroundColor = .clear
      vc.scrollViewDelegate = self
      vc.getScrollView().contentInset = UIEdgeInsets.init(top: categoryViewHeight, left: 0, bottom: 0, right: 0)
      vc.getScrollView().scrollIndicatorInsets = vc.getScrollView().contentInset
      
      func displaySubViewController() {
        vc.view.alpha = 0
        view.addSubview(vc.view)
        view.bringSubviewToFront(categoryContainer)
        
        vc.prepareUI()
        vc.view.snp.makeConstraints { maker in
          maker.leading.top.trailing.bottom.equalTo(view)
        }
        addChild(vc)
        vc.didMove(toParent: self)

        if #available(iOS 11.0, *) {
          // MARK: - [WARNING]: This content-offset stuff may not be necessary in future iOS
          // reset scroll view offset.
          let delta = self.navigationController!.navigationBar.height + UIApplication.shared.statusBarFrame.height + categoryViewHeight
          vc.getScrollView().setContentOffset (
            CGPoint(x: 0, y: -delta),
            animated: false
          )
        }

        UIView.animate(withDuration: 0.3) {
          vc.view.alpha = 1
        }
        currentSubViewController = vc
      }

      if currentSubViewController != nil {
        UIView.animate(withDuration: 0.3, animations: {
          self.currentSubViewController!.view.alpha = 0
        }) { _ in
          if #available(iOS 11.0, *) {

          } else {
            self.currentSubViewController!.getScrollView().setContentOffset(CGPoint.zero, animated: false)
          }
          self.currentSubViewController!.view.removeFromSuperview()
          self.currentSubViewController!.removeFromParent()
          self.currentSubViewController = nil
          displaySubViewController()
        }
      } else {
        displaySubViewController()
      }
    }
  }
  
  // MARK: - Public vars
  
  
  
  // MARK: - Lifecycle
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    prefersLargeTitles = true
    
    prepareUI()
    displaySubViewController(index: 0)
  }
  
  override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    
    UIView.animate(withDuration: 0.3) {
      self.categoryView.alpha = 1
    }
  }
  
  override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    categoryView.alpha = 0
  }
  
  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
  
  // MARK: - IBActions
  
  @IBAction func showPlayHistory(_ sender: UIBarButtonItem) {
    if let playHistoryNavigationController = UIStoryboard(name: "Player", bundle: nil).instantiateViewController(withIdentifier: "PlayHistoryNavigationController") as? BaseNavigationController {
      playHistoryNavigationController.dismissDelegate = self
      present(playHistoryNavigationController, animated: true)
    }
  }
  
  // MARK: - Public methods
  
  
}

// MARK: - VIPChildViewControllerScrollViewDelegate

extension VIPHomeViewController: VIPChildViewControllerScrollViewDelegate {
  func vipChildViewController(_ childViewController: UIViewController, didScroll contentOffsetY: CGFloat) {
    if #available(iOS 11.0, *) {
      // disable category switching while use pull the scrollview too much
      categoryView.isUserInteractionEnabled = (navigationController!.navigationBar.height <= 96 + 1)
      
      // re-position category view
      let delta = 96 + UIApplication.shared.statusBarFrame.height + categoryViewHeight // 96 is height of large title navbar
      if contentOffsetY <= -delta {
        topViewTopConstraint.constant = -delta - contentOffsetY
      } else {
        topViewTopConstraint.constant = 0
      }
    }
  }
}

// MARK: - CategoryViewDelegate

extension VIPHomeViewController: CategoryViewDelegate {
  func didSelect(index: Int) {
    displaySubViewController(index: index)
  }
}

// MARK: - BaseNavigationControllerDismissDelegate

extension VIPHomeViewController: BaseNavigationControllerDismissDelegate {
  func dismiss(navigationController: BaseNavigationController, completion: (() -> Void)?) {
    dismiss(animated: true, completion: completion)
  }
}
